package top.iszsq.config.format;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 在默认情况下，jackson会将joda time序列化为较为复杂的形式，不利于阅读，并且对象较大。
 * <p>
 * JodaTime 序列化的时候可以将datetime序列化为字符串，更容易读
 * @author zsq
 * @date 2021/6/9 11:14
 **/
public class DateTimeSerializer extends JsonSerializer<LocalDateTime> {

    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        if (value != null) {
            jgen.writeString(value.format(dateFormatter));
        }
    }

}
